package org.chen.spring.cloud.finchley.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.chen.spring.cloud.finchley.zuul.base.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * @author chensj
 * @date 2020-02-09 07:32
 */
public class SecondPreFilter extends ZuulFilter {

  private static final Logger log = LoggerFactory.getLogger(SecondPreFilter.class);

  @Override
  public String filterType() {
    return PRE_TYPE;
  }

  @Override
  public int filterOrder() {
    return 1;
  }

  @Override
  public boolean shouldFilter() {
    return true;
  }

  @Override
  public Object run() throws ZuulException {
    log.info("进入{}过滤器，开始检查参数a", getClass());
    // 从RequestContext获取Context
    RequestContext context = RequestContext.getCurrentContext();
    // 获取请求
    HttpServletRequest request = context.getRequest();
    // 获取参数a
    String a = request.getParameter("a");
    if (StringUtils.isEmpty(a)) {
      // 对该请求禁止路由，也就是禁止访问下游服务
      context.setSendZuulResponse(false);
      // 用来给后面的 Filter 标识，是否继续执行
      context.set(Constants.LOGIC_IS_SUCCESS, false);
      // 设置ResponseBody提供给PostFilter使用
      context.setResponseBody(String.format(Constants.ERROR_RESPONSE_BODY, "参数a未定义"));
      return null;
    }
    // 设置避免出现空指针
    context.set(Constants.LOGIC_IS_SUCCESS, true);
    return null;
  }
}
